#include <stdio.h>
#include <stdlib.h>

#define NUM 8

typedef struct node{
	int data;
	struct node *next;
} node_t;

void insert_node(node_t **head, int data)
{
	node_t *new = (node_t *)malloc(sizeof(node_t));
	new->data = data;

	if (!*head)
		*head = new;
	else {
		new->next = *head;
		*head = new;
	}
}

inline void print_list(node_t *p)
{
	while (p) {
		printf("%d ", p->data);
		p = p->next;
	}
	printf("\n");
}

void reverse_list(node_t **head)
{
	node_t *pos = NULL, *pre = NULL;

	if (!*head)
		return;
	pos = (*head)->next;
	pre = *head;
	while (pos) {
		pre->next = pos->next;
		pos->next = *head;
		*head = pos;
		pos = pre->next;
	}
}

node_t *reverse_list_2(node_t *head)
{
	node_t * prh = NULL, *pos, *pre = NULL;

	pos =  head;
	while (pos) {
		node_t *next = pos->next;

		if (!next)
			prh = pos;

		pos->next = pre;
		
		pre = pos;
		pos = next;
	}

	return prh;
}

int main()
{
	node_t *head = NULL, *h2;
	int i;

	for (i = 0; i < NUM; i++) {
		insert_node(&head, i);
	}
	print_list(head);
//	reverse_list(&head);
	h2 = reverse_list_2(head);
	print_list(h2);
	
	return 0;
}

